/**
 * 创建全局WebSocket连接并挂载到全局对象上
 */
function createConnectionAndLoadWindow() {
    if (window.socket) {
        console.log("已进行连接");
        return;
    }
    let roomCode = ZhhSessionStorage_getItem('roomCode');
    let userName = ZhhSessionStorage_getItem('userName');
    let param = {};
    if (roomCode) {
        param.roomCode = roomCode;
    }
    if (userName) {
        param.userName = userName;
    }
    let userInfo = JSON.parse(ZhhSessionStorage_getItem("userInfo"));
    if (userInfo) {
        param.userId = userInfo.userId;
    }
    let queryString = "";
    if (Object.keys(param).length > 0) {
        queryString = '?' + new URLSearchParams(param)
    }
    // 创建 WebSocket 连接
    const socket = new WebSocket('/zhh/joinRoom' + queryString);
    socket.onopen = function () {
        // console.log('WebSocket 连接已打开');
        /**
         * 获取房间信息并补充棋盘数据
         */
        let roomCode = ZhhSessionStorage_getItem('roomCode');
        getRoomDetail(roomCode).then(response => {
            let chess = response.chessboard;
            ChessBoardData_fillData(chess);
            fillChess(chess);
        })

    };
    socket.onmessage = (event) => {
        let messageBody = event.data;
        webSocketOnMessage(JSON.parse(messageBody));
    };
    socket.onclose = function () {
        console.error('WebSocket 连接关闭');
        window.socket = null;
    };
    socket.onerror = function (error) {
        console.error('WebSocket 发生错误:', error);
    };
    // 将 socket 对象挂载到全局对象上
    window.socket = socket;
    return socket;
}


function webSocketOnMessage(content) {
    let tittle = content.tittle;
    if (tittle === 'MESSAGE') {
        addMessageContent(false, content.message, content.sender.userName, content.sender.role);
    } else if (tittle === 'EXCEPTION') {
        exceptionHandler(content);
    } else if (tittle === 'BROADCAST') {
        addSystemMessageContent(content.message);
    } else if (tittle === 'SYSTEM') {
        systemMessage(content);
    } else if (tittle === 'PLAY_CHESS') {
        playChess(content);
    } else if (tittle === 'LOSE' || tittle === 'WIN') {
        switch (tittle) {
            case 'LOSE':
                loser(content);
                break;
            case 'WIN':
                winner(content);
                break;
        }
        ChessBoardData_reset();
        resetChessboard();
        changeReadyButton(JSON.parse(ZhhSessionStorage_getItem('userInfo')));
        refreshRoomDetail(ZhhSessionStorage_getItem('roomCode'));
        // 重新开始
        selfTurn = false;

    }
}

function exceptionHandler(content) {
    popUpMessageShow("房间不存在");
    if (window.location.pathname !== '/zhh/view/index') {
        setTimeout(() => {
            window.location.href = '/zhh/view/index';
        }, 1000);
    }
}

function systemMessage(content) {
    let currentUserInfo = content.currentUser;
    if (content.code === 1) {
        // 本人加入房间
        ZhhSessionStorage_setItem("userInfo", JSON.stringify(currentUserInfo));
        displayLabelUser(currentUserInfo, currentUserInfo);
        addReadyButton();
    } else if (content.code === 5) {
        // 操作异常
        alert(content.operate);
    } else if (content.code === 3) {
        // 游戏开始
        addSystemMessageContent("游戏开始");
    } else if (content.code === 6) {
        // 玩家先后手顺序
        let currentUser = content.currentUser;
        if (currentUser.isFirst) {
            selfTurn = true;
            popUpMessageShow('你是先手');
        } else {
            selfTurn = false;
            popUpMessageShow("你是后手");
        }
    } else if (content.code === 7) {
        let f = JSON.parse(content.operate);
        if (f.b) {
            setFirstPlay(1);
            currentTurnTo(2);
        }
        if (f.w) {
            setFirstPlay(2);
            currentTurnTo(1);
        }
    } else if (content.code === 8) {
        displayLabelUser(content.currentUser, content.currentUser);
    }
}

function playChess(content) {
    let chess = ChessBoardData_getChessDrawPosition(content.x, content.y);
    let chessPosition = {
        chessDrawX: chess.drawX,
        chessDrawY: chess.drawY
    };
    let chessData = {
        color: ChessBoardData.blackChessColor
    }
    if (content.color === 1) {
        chessData.color = ChessBoardData.blackChessColor;
    } else if (content.color === 2) {
        chessData.color = ChessBoardData.whiteChessColor;
    }
    let success = ChessBoardData_playChess(content.x, content.y, content.color);
    if (!success) {
        console.error('本地棋盘中已有棋子');
    }
    drawChess(window.chessboardCanvas, chessPosition, chessData);
    selfTurn = true;
    currentTurnTo(content.color);
}

function winner(content) {
    alert('你赢了');
}

function loser(content) {
    alert('你输了');
}

function refreshRoomDetail(roomCode) {
    getRoomDetail(roomCode).then(response => {
        let roomInfo = response;
        // 黑白分数
        let blackScore = roomInfo.blackScore;
        let whiteScore = roomInfo.whiteScore;
        // 当前先手
        let firstStep = roomInfo.firstStep;
        // 棋盘信息
        let chessboardData = roomInfo.chessboard;
        ChessBoardData_fillData(chessboardData);
        fillChess(chessboardData);
        changeBlackScore(blackScore);
        changeWhiteScore(whiteScore);
        setFirstPlay(firstStep ? 1 : 2);

        let blackUser = roomInfo.blackUser;
        let whiteUser = roomInfo.whiteUser;
        displayLabelUser(blackUser, whiteUser);

    })

}

function changeBlackScore(score) {
    document.getElementById("blackScoreSpan").innerText = score.toString().padStart(3, '0');
}

function changeWhiteScore(score) {
    document.getElementById("whiteScoreSpan").innerText = score.toString().padStart(3, '0');
}